import React, { Component } from "react";
import { Toast, InputItem } from "antd-mobile";
import yhTools from "../../tools/yh";
import { ThemeLife, ThemeDefault } from "../../tools/theme";
import "./sendMSGCode.scss";

let OBJS = {};
class SendMSGCode extends Component {
	constructor(props) {
		super(props);
		this.state = {
			msgSubTitle: "", // 副标题
			showMsgBox: true, // 控制展示验证码弹框
			countDownstatus: "able", // 按钮的状态,
			buttDisabled: true,
			spaceID: "", // 随记生成一个计数
			tempSeconds: this.props.seconds ? this.props.seconds : 120,
			timeText: `${this.props.seconds ? this.props.seconds : 120}秒`,
			seconds: this.props.seconds ? this.props.seconds : 119, //短信验证码倒计时
			getCode: false, //显示发送验证码
			codeArr: Array.from({ length: 6 }, () => ""),
			codeType: 6,
			msgCode: "" //输入的验证码
		};
		this.timer = null;
		this.isOpen = true;
	}

	componentDidMount() {
		// this.countdown();
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.showMsgBox == false) {
			this.timer = null;
			this.setState({
				codeArr: Array.from({ length: 6 }, () => ""),
				msgCode: "",
				timeText: `${this.state.tempSeconds}秒`,
				seconds: this.state.tempSeconds - 1 //短信验证码倒计时
			});
		} else {
			this.setState({ seconds: this.state.tempSeconds - 1 });
		}
	}

	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		clearInterval(this.timer);
	}

	//倒计时
	countdown() {
		this.isOpen = false;
		const _this = this;
		let { seconds } = this.state;
		this.timer = setInterval(() => {
			if (seconds < 1) {
				clearInterval(this.timer);
				this.isOpen = true;
				_this.setState({
					seconds: _this.state.tempSeconds,
					timeText: "重新获取"
				});
			} else {
				seconds--;
				_this.setState({
					seconds,
					timeText: `${seconds}秒`
				});
			}
		}, 1000);
	}

	//重新发送验证码
	againYZM() {
		if (!this.isOpen) {
			return false;
		}
		// this.countdown();
		this.props.getYZMCode();
	}

	/**
	 * 键盘事件
	 */
	keyboardEvent = obj => {
		let winHeight = document.documentElement.clientHeight;
		document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
			winHeight * obj.heightper + "px";
	};

	/**
	 * 发送短信验证码
	 */
	sendVerificationCode(objs) {
		OBJS = objs;
		Toast.loading("加载中...", 100);
		let _that = this;
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				// Toast.info(res.message, 2);
				_that.setState(
					{
						showMsgBox: true,
						countDownstatus: "able",
						msgSubTitle: res.data.sendSuccessPhone
					},
					() => {
						document.getElementById(
							`keybordb_${this.state.spaceID}`
						).style.height = 0;
					}
				);
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	/**
	 * 提交按钮
	 */
	submitButtClick = () => {
		if (this.state.buttDisabled) {
			// 表单验证
			return;
		}
		let messageCode = this.state.messageCodeValue;
		this.props.submitCode(messageCode);
	};

	/**
	 * 关闭弹框
	 */
	handleClose = () => {
		let _that = this;
		clearInterval(this.timer);
		this.timer = null;
		this.setState({
			timeText: `${_that.state.tempSeconds}秒`,
			seconds: _that.state.tempSeconds - 1, //短信验证码倒计时
			showMsgBox: false,
			countDownstatus: "disable",
			msgSubTitle: "",
			buttDisabled: true
		});
		this.props.closeSendModal();
	};

	/**
	 * 输入框输入回调
	 */
	inputChangeAction(value) {
		if (value.length >= 6) {
			this.setState({
				buttDisabled: false,
				messageCodeValue: value
			});
		} else {
			this.setState({
				buttDisabled: true,
				messageCodeValue: value
			});
		}
	}

	/**
	 * 点击获取验证码 反馈回调
	 * @param {} res
	 */
	countDownCallBack() {
		this.sendVerificationCode(OBJS);
	}

	render() {
		// 倒计时组件
		let { msgCode, codeArr, codeType, seconds, tempSeconds } = this.state;
		return (
			<div className="send-MSG-code">
				{this.props.showMsgBox ? (
					<div>
						<div className="maskView"></div>
						<div className="contentView">
							<div className="messagebox">
								<div className="messageBoxHeader">
									<div className="title"></div>
									<div className="close" onClick={this.handleClose}></div>
								</div>
								<div className="msg_con">
									<div className="subtitle">验证手机号</div>
									<div className="tips">验证码已发送至手机</div>
									<div className="tips">{this.props.sendSuccessPhone}</div>
									<div className="messageBoxContent flexBetween">
										<div className="login-area">
											<div className="input-area">
												{codeArr.map((item, index) => {
													return (
														<div
															className={
																msgCode.length >= index
																	? "input-code input-code-value"
																	: "input-code"
															}
															key={index}
															onClick={this.inputFocus.bind(this)}
														>
															{item}
														</div>
													);
												})}
											</div>
											<InputItem
												className="input-item-code"
												ref={el => (this.inputRef = el)}
												value={msgCode}
												type="money"
												maxLength={codeType}
												disabledKeys={["."]}
												onChange={this.getInputValue.bind(this)}
											/>

											<div
												className={
													seconds < tempSeconds
														? "tips-area"
														: "tips-area tips-area-btn"
												}
												onClick={this.againYZM.bind(this)}
											>
												{seconds < tempSeconds
													? seconds + "s后重新发送"
													: "重新发送"}
											</div>
										</div>
									</div>
									<ThemeDefault>
										<div
											className={
												this.state.buttDisabled
													? "messageBoxFooter grayButtStyle"
													: "messageBoxFooter blueButtStyle"
											}
											onClick={this.submitButtClick}
										>
											{" "}
											确定
										</div>
									</ThemeDefault>
									<ThemeLife>
										<div
											className={
												this.state.buttDisabled
													? "messageBoxFooter grayButtStyle"
													: "messageBoxFooter blueButtStyleLife"
											}
											onClick={this.submitButtClick}
										>
											{" "}
											确定
										</div>
									</ThemeLife>
								</div>
								<div id={"keybordb_" + this.state.spaceID}></div>
							</div>
						</div>
					</div>
				) : null}
			</div>
		);
	}
	//监听输入的验证码，到6位提交数据
	getInputValue(value) {
		this.inputChangeAction(value);
		// 校验输入内容
		let arrayCode = Array.from(value.replace(/\s/g, ""));
		if (arrayCode.length > this.state.codeType) {
			//高于6位，截取6位
			arrayCode = arrayCode.slice(0, this.state.codeType);
			//TODO 7
			value = value.slice(0, this.state.codeType + 1);
		}
		let oldCodeArr = Array.from({ length: this.state.codeType }, () => "");
		oldCodeArr.splice(0, arrayCode.length, ...arrayCode);
		this.setState({
			codeArr: oldCodeArr,
			msgCode: value
		});
	}
	//获取焦点，弹出输入框
	inputFocus() {
		this.inputRef.focus();
	}
}
export default SendMSGCode;
